package com.api.common.manager;

import com.api.common.constant.APIInterfaceMqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author: 崔老爷
 * Date: 2024/10/16 11:13
 * @Description: 发送接口日志到队列
 */
@Component
@Slf4j
public class APIInterfaceLogManager {
    @Resource
    private RabbitTemplate rabbitTemplate;
    public  void  sendMessage(String message){
        try {
            rabbitTemplate.convertAndSend(
                    APIInterfaceMqConstant.API_INTERFACE_LOG_EXCHANGE,
                    APIInterfaceMqConstant.API_INTERFACE_LOG_ROUTE_KEY,
                    message,
                    correlationData -> {
                        return correlationData;
                    }
            );
        }catch (Exception e){
            log.error("发送MQ消息失败: {}", message, e);
            // 降级：写入本地文件或数据库
        }
    }
    // 配置确认回调
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                log.error("消息发送失败: {}, cause: {}", correlationData, cause);
            }
        });
    }
}
